package com.vone.vmq;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.vone.qrcode.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NeNotificationService2  extends NotificationListenerService {
    private String TAG = "NeNotificationService2";
    private String host = "";
    private String key = "";
    private Thread newThread = null;
    private PowerManager.WakeLock mWakeLock = null;

    int id = 1000;
    //申请设备电源锁
    @SuppressLint("InvalidWakeLockTag")
    public void acquireWakeLock(Context context) {
        if (null == mWakeLock)
        {
            PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE, "WakeLock");
            if (null != mWakeLock)
            {
                mWakeLock.acquire();
            }
        }
    }
    //释放设备电源锁
    public void releaseWakeLock() {
        if (null != mWakeLock)
        {
            mWakeLock.release();
            mWakeLock = null;
        }
    }
    //心跳进程
    public void initAppHeart(){
        Log.d(TAG, "开始启动心跳线程");
        if (newThread!=null){
            return;
        }
        acquireWakeLock(this);
        newThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "心跳线程启动！");
                while (true){

                    SharedPreferences read = getSharedPreferences("vone", MODE_PRIVATE);
                    host = read.getString("host", "");
                    key = read.getString("key", "");

                    //这里写入子线程需要做的工作
                    String t = String.valueOf(new Date().getTime());
                    String sign = md5(t+key);


                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().url("http://"+host+"/appHeart?t="+t+"&sign="+sign).method("GET",null).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            final String error = e.getMessage();
                            Handler handlerThree=new Handler(Looper.getMainLooper());
                            handlerThree.post(new Runnable(){
                                public void run(){
                                    Toast.makeText(getApplicationContext() ,"心跳状态错误，请检查配置是否正确!"+error,Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        //请求成功执行的方法
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            Log.d(TAG, "onResponse heard: "+response.body().string());
                        }
                    });
                    try {
                        Thread.sleep(30*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        newThread.start(); //启动线程
    }




    //当收到一条消息的时候回调，sbn是收到的消息
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.d(TAG, "接受到通知消息");
        SharedPreferences read = getSharedPreferences("vone", MODE_PRIVATE);
        host = read.getString("host", "");
        key = read.getString("key", "");


        Notification notification = sbn.getNotification();
        String pkg = sbn.getPackageName();
        if (notification != null) {
            Bundle extras = notification.extras;
            if (extras != null) {
                String title = extras.getString(NotificationCompat.EXTRA_TITLE, "");
                String content = extras.getString(NotificationCompat.EXTRA_TEXT, "");
                Log.d(TAG, "**********************");
                Log.d(TAG, "包名:" + pkg);
                Log.d(TAG, "标题:" + title);
                Log.d(TAG, "内容:" + content);
                Log.d(TAG, "**********************");


                if (pkg.equals("com.eg.android.AlipayGphone")){
                    if (content!=null && !content.equals("")) {
                        if (content.indexOf("通过扫码向你付款")!=-1 || content.indexOf("成功收款")!=-1){
                            String money = getMoney(content);
                            if (money!=null){
                                Log.d(TAG, "onAccessibilityEvent: 匹配成功： 支付宝 到账 " + money);
                                appPush(2, Double.valueOf(money));
                            }
                        }

                    }

                }else if(pkg.equals("com.tencent.mm")){

                    if (content!=null && !content.equals("")){
                        if (title.equals("微信支付") || title.equals("微信收款助手") || title.equals("微信收款商业版")){
                            String money = getMoney(content);
                            if (money!=null){
                                Log.d(TAG, "onAccessibilityEvent: 匹配成功： 微信到账 "+ money);
                                appPush(1,Double.valueOf(money));
                            }

                        }
                    }

                }else if(pkg.equals("com.vone.qrcode")){

                    if (content.equals("这是一条测试推送信息，如果程序正常，则会提示监听权限正常")){
                        Handler handlerThree=new Handler(Looper.getMainLooper());
                        handlerThree.post(new Runnable(){
                            public void run(){
                                Toast.makeText(getApplicationContext() ,"监听正常！",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }



            }
        }

    }
    //当移除一条消息的时候回调，sbn是被移除的消息
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {

    }
    //当连接成功时调用，一般在开启监听后会回调一次该方法
    @Override
    public void onListenerConnected() {
        Log.d(TAG, "onListenerConnected");
        //开启心跳线程
//        initAppHeart();

        Handler handlerThree = new Handler(Looper.getMainLooper());
        handlerThree.post(new Runnable(){
            public void run(){
                Toast.makeText(getApplicationContext() ,"监听服务开启成功！",Toast.LENGTH_SHORT).show();
            }
        });


    }





    public void appPush(int type,double price){
//        SharedPreferences read = getSharedPreferences("vone", MODE_PRIVATE);
//        host = read.getString("host", "");
//        key = read.getString("key", "");
//
//        Log.d(TAG, "onResponse  push: 开始:"+type+"  "+price);
//
//        String t = String.valueOf(new Date().getTime());
//        String sign = md5(type+""+ price + t + key);
//        String url = "http://"+host+"/appPush?t="+t+"&type="+type+"&price="+price+"&sign="+sign;
//        Log.d(TAG, "onResponse  push: 开始:"+url);
//
//        OkHttpClient okHttpClient = new OkHttpClient();
//        Request request = new Request.Builder().url(url).method("GET",null).build();
//        Call call = okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onResponse  push: 请求失败");
//
//            }
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//                Log.d(TAG, "onResponse  push: "+response.body().string());
//
//            }
//        });

        if(type==2)queryOrderList(price);
        //if(type==2)releaseMoney("C157317308032832",0.01);



    }

    public static String getMoney(String content){

        int index = content.indexOf("]");
        if (index!=-1){
            content = content.substring(index+1);
        }


        Pattern p = Pattern.compile("([0-9]\\d*\\.?\\d*)|(0\\.\\d*[0-9])");
        Matcher m = p.matcher(content);
        boolean result = m.find();
        String find_result = null;
        if (result) {
            find_result = m.group(1);
        }
        return find_result;
    }
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


/******************************************************************/

private void doLogin(final double pushMoney){

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormBody.Builder()
            .add("username",getAccount())
            .add("password",getLoginPwd())
            .build();

//        Headers header = new Headers.Builder()
//                .add("","")
//                .build();

    Request request = new Request.Builder()
            .url("http://www.otc888.cc/uc/login")
            .method("POST",requestBody)
//                .headers(header)
            .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d(TAG, "onResponse  doLogin: 请求失败");
            //myHandler.sendEmptyMessage(MSG_RERUSET_ERROR);

        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(!response.isSuccessful()){
                //myHandler.sendEmptyMessage(MSG_RERUSET_ERROR);
                return;
            }

            String jsonStr = response.body().string();
            Log.d(TAG, "onResponse  doLogin: "+jsonStr);
            try {
                JSONObject jsonObject = new JSONObject(jsonStr);
                int code = jsonObject.getInt("code");
                if(code==0){
                    JSONObject dataJson = jsonObject.getJSONObject("data");
                    String token = dataJson.getString("token");
                    Log.d(TAG, "onResponse  token: " + token);
                    savaToken(token);
                    queryOrderList(pushMoney);
                }else{

                }


            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });
}

    private void queryOrderList(final double pushMoney){

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("status","PAID")
                .add("pageSize","20")
                .add("pageNo","0")
                .build();

        Headers header = new Headers.Builder()
                .add("x-auth-token",getToken())
                //.add("x-auth-token","2f81cc44-18ca-422c-a1e7-f31d16f14292")
                //.add("access-auth-token","02fe5cc0a1d620402d400cecb2f57381")
                .build();

        Request request = new Request.Builder()
                .url("http://www.otc888.cc/otc/gctorder/self")
                .method("POST",requestBody)
                .headers(header)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onResponse  queryOrderList: 请求失败");
                //Toast.makeText(NeNotificationService2.this, "请求失败", Toast.LENGTH_SHORT).show();

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(!response.isSuccessful()){
                    //Toast.makeText(NeNotificationService2.this, response.message(), Toast.LENGTH_SHORT).show();
                    return;
                }

                String jsonStr = response.body().string();
                Log.d(TAG, "onResponse  queryOrderList: "+jsonStr);
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    int code = jsonObject.getInt("code");
                    if(code==0){
                        JSONObject dataJson = jsonObject.getJSONObject("data");
                        JSONArray contentArr = dataJson.getJSONArray("content");
                        if(contentArr==null || contentArr.length()<=0){
                            Log.d(TAG, "onResponse  JSONArray为空");
                        }else{
                            String orderSn = contentArr.getJSONObject(0).getString("orderSn");
                            double money = contentArr.getJSONObject(0).getDouble("money");
                            if(pushMoney==money){
                                releaseMoney(orderSn,money);
                            }
                        }

                    }
                    else if(code==4000){
                        //Toast.makeText(MainActivity.this, "登录已失效，请重新登录", Toast.LENGTH_SHORT).show();
                        doLogin(pushMoney);
                    }
                    else{
//                        String message = jsonObject.getString("message");

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void releaseMoney(String orderSn,final double money){

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("orderSn",orderSn)
                .add("jyPassword",getPayPwd())
                .add("money",money+"")
                .build();

        Headers header = new Headers.Builder()
                //.add("x-auth-token",getToken())
                .add("x-auth-token",getToken())
                .build();

        Request request = new Request.Builder()
                .url("http://www.otc888.cc/otc/gctorder/release")
                .method("POST",requestBody)
                .headers(header)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onResponse  releaseMoney: 请求失败");
                //Toast.makeText(NeNotificationService2.this, "请求失败", Toast.LENGTH_SHORT).show();

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(!response.isSuccessful()){
                    //Toast.makeText(NeNotificationService2.this, response.message(), Toast.LENGTH_SHORT).show();
                    return;
                }

                String jsonStr = response.body().string();
                Log.d(TAG, "onResponse  releaseMoney: "+jsonStr);
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    int code = jsonObject.getInt("code");
                    if(code==0){
                        //Toast.makeText(NeNotificationService2.this, "放行成功 money=="+money, Toast.LENGTH_LONG).show();
                        push(money);
                    }
//                    else if(code==4000){
//                        Toast.makeText(MainActivity.this, "登录已失效，请重新登录", Toast.LENGTH_SHORT).show();
//                    }
                    else{
//                        String message = jsonObject.getString("message");

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public void push(double money){
        Notification mNotification;
        NotificationManager mNotificationManager;
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("1",
                    "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);
            channel.setLightColor(Color.GREEN);
            channel.setShowBadge(true);
            mNotificationManager.createNotificationChannel(channel);

            Notification.Builder builder = new Notification.Builder(this,"1");

            mNotification = builder
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setTicker("放行成功:money=="+money)
                    .setContentTitle("放行成功")
                    .setContentText("放行成功:money=="+money)
                    .build();
        }else{
            mNotification = new Notification.Builder(NeNotificationService2.this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setTicker("放行成功:money=="+money)
                    .setContentTitle("放行成功")
                    .setContentText("放行成功:money=="+money)
                    .build();
        }

        //Toast.makeText(MainActivity.this, "已推送信息，如果权限，那么将会有下一条提示！", Toast.LENGTH_SHORT).show();



        mNotificationManager.notify(id++, mNotification);
    }


    private String getToken(){
        SharedPreferences write = getSharedPreferences("vone", MODE_PRIVATE);
        return write.getString("token","");
    }


    private void savaToken(String token){
        SharedPreferences write = getSharedPreferences("vone", Context.MODE_PRIVATE);
        write.edit().putString("token",token).commit();
    }
    private String getAccount(){
        SharedPreferences write = getSharedPreferences("vone", Context.MODE_PRIVATE);
        return write.getString("account","");
    }
    private String getLoginPwd(){
        SharedPreferences write = getSharedPreferences("vone", Context.MODE_PRIVATE);
        return write.getString("loginPwd","");
    }
    private String getPayPwd(){
        SharedPreferences write = getSharedPreferences("vone", Context.MODE_PRIVATE);
        return write.getString("payPwd","");
    }


}
